const fs = require('fs')

import { ObjectId, MongoClient } from 'mongodb'
import YAML from 'yamljs'

import BaseResult from '../lib/BaseResult'

const { mongo } = YAML.parse(fs.readFileSync('./server/config.yaml').toString());
const url = mongo.host;


class ErrorController {
    static async report(ctx) {
        let data = ctx.request.body;
        // data.id
        return new Promise((resolve) => {
            MongoClient.connect(url, function(err, db) {
                if (err) throw err;
                console.log('数据库已创建');
                var dbo = db.db("rmos");
                // var myobj = { name: "菜鸟教程", url: "www.runoob" };
                dbo.collection("error").insertOne(data, function(err, res) {
                    if (err) throw err;
                    // console.log("文档插入成功");
                    // ctx.body = "文档插入成功";
                    ctx.body = new BaseResult(0, 0, null);
                    resolve();
                    db.close();
                });
            });

        })
    }
    static async reportSimple(ctx) {
        let data = ctx.request.body;
        // data.id
        return new Promise((resolve) => {
            MongoClient.connect(url, function(err, db) {
                if (err) throw err;
                console.log('数据库已创建');
                var dbo = db.db("rmos");
                // var myobj = { name: "菜鸟教程", url: "www.runoob" };
                dbo.collection("error").insertOne(data, function(err, res) {
                    if (err) throw err;
                    // console.log("文档插入成功");
                    // ctx.body = "文档插入成功";
                    ctx.body = new BaseResult(0, 0, null);
                    resolve();
                    db.close();
                });
            });

        })
    }
    static async detail(ctx) {}
    static async register(ctx) {}
    static async list(ctx) {
        return new Promise((resolve) => {
            MongoClient.connect(url, function(err, db) {
                if (err) throw err;
                var dbo = db.db("rmos");
                dbo.collection("error").find({}).limit(10).toArray(function(err, result) { // 返回集合中所有数据
                    if (err) throw err;
                  //  console.log(result);
                    ctx.body = new BaseResult(0, 0, result);
                    resolve()
                    db.close();
                });
            });
        })
    }
}
export default ErrorController;